import {
  globalConfig,
  resourceApiAliasConfig,
  realPageFilePathKeyFuc,
  getCurResourceLastCode,
} from "@gd-accbuild-core/config";
import pcadmin_globalStyles from "@gd-accbuild-core/theme-chalk/pc-admin/js.module.scss";

/**
 * 获取templateKey: 根据模板的uiOptions中的属性 通过 templateName反向 获取templateKey
 * @param {Object} matchedTemplateProps
 */
export const getTemplateKey = (matchedTemplateProps,templateNameAlias="templateName") => {
  let suffix = "";
  if (!matchedTemplateProps || !matchedTemplateProps?.templateName) {
    return "";
  }
  const isSingleVmTemplate =
    (!matchedTemplateProps.templateProps?.filter_tableCommonAttr?.vmCode &&
      matchedTemplateProps.templateProps?.tableCommonAttr?.vmCode) ||
    (matchedTemplateProps.templateProps?.filter_tableCommonAttr?.vmCode &&
      !matchedTemplateProps.templateProps?.tableCommonAttr?.vmCode);
  const isDoubleVmTemplate =
    matchedTemplateProps.templateProps?.filter_tableCommonAttr?.vmCode &&
    matchedTemplateProps.templateProps?.tableCommonAttr?.vmCode;
  if (isSingleVmTemplate) {
    suffix = "";
  } else if (isDoubleVmTemplate) {
    suffix = "_filter";
  }
  return `${matchedTemplateProps[templateNameAlias]}${suffix}`;
};
/**
 * 获取布局容器的样式 globalConfig.targetPlatform
 */
export const getLayoutContainerStyle = (targetPlatform) => {
  const pageContainerStyle =
    targetPlatform === "pc-admin"
      ? {
          height: `100vh - ${pcadmin_globalStyles.accbuildPageTopWindowContainerHeight}`,
        }
      : {};
  const bizContainerStyle =
    targetPlatform === "pc-admin"
      ? {
          height: `calc(100vh - ${pcadmin_globalStyles.accbuildPageTagsContainerHeight} - ${pcadmin_globalStyles.accbuildPageTopWindowContainerHeight})`,
          padding: pcadmin_globalStyles.accbuildDefaultContainerGutter,
        }
      : {};
  return {
    pageContainerStyle,
    bizContainerStyle,
  };
};

/**
 * 获取模板页面的栅格布局信息
 */
export const getPageTemplateLayoutConfigInfo = ({ resource, idxRoute = [] }) => {
  //TODO:FIXME: 设计时需要代理 targetPlatform
  const { pageContainerStyle, bizContainerStyle } = getLayoutContainerStyle(globalConfig.targetPlatform);

  const uiOptionsKeyAlias = resourceApiAliasConfig["uiOptionsKeyAlias"];
  const pageLayoutConfigKeyAlias = resourceApiAliasConfig["pageLayoutConfigKeyAlias"];
  let pageLayoutConfig = resource[uiOptionsKeyAlias]?.[pageLayoutConfigKeyAlias] ?? {};
  //console.log("111这里都有吗", resource.name);
  if (Object.keys(pageLayoutConfig).length === 0) {
    //注意带下划线前缀的属性不是组件属性
    pageLayoutConfig = {
      span: 24, //递归嵌套grid布局容器时的父col宽度
      rowConfig: {
        gutter: 0,
        justify: "start",
        align: "top",
        style: pageContainerStyle,
      },
      //allColConfigs数组里面的元素有两种形式: 1. 递归嵌套grid布局容器 2. CRUD组件。//CRUD组件是结束递归的条件
      allColConfigs: [
        {
          span: 24,
          offset: 0,
          xs: undefined,
          sm: undefined,
          md: undefined,
          lg: undefined,
          xl: undefined,
          style: bizContainerStyle,
          //插槽CRUD组件id;"单CRUD组件"页面的id不需要,取pageUiTemplateConfigs里面idx=0即可
          _slotCrudCompId: "",
          // 暂定用于CRUD组件里面的插槽
          _children: [],
        },
      ],
    };
    //console.log(pageLayoutConfig, "pageLayoutConfig==", resource.name, resource);
    resource[uiOptionsKeyAlias][pageLayoutConfigKeyAlias] = pageLayoutConfig;
  }
  //console.log("打印静态资源", resource, pageLayoutConfig, idxRoute);
  if (!pageLayoutConfig?.rowConfig?.style) {
    pageLayoutConfig.rowConfig.style = pageContainerStyle;
  }
  idxRoute.forEach((el) => {
    pageLayoutConfig = pageLayoutConfig[el];
  });
  return pageLayoutConfig;
};

/**
 * 模板的Vm配置的匹配规则,默认匹配本身,匹配不到找tableCommonAttr下面
 */
const getTemplateVmConfigInfo = ({ config, idx, overrideParams }) => {
  const dataFromType = config?.dataFromType ?? config?.templateProps?.tableCommonAttr?.dataFromType;
  //模板配置的key规律是 dataFromType 的首字母小写
  const dataFromTypeCfgKey = dataFromType[0].toLocaleLowerCase() + dataFromType.substring(1);
  const retInfo = { isTemplateVmConfigMatched: false };
  if (["VmCode", "HttpService"].includes(config.dataFromType)) {
    retInfo.isTemplateVmConfigMatched = true;
    retInfo.config = {
      ...config,
      templateIdx: idx,
      [dataFromTypeCfgKey]: config[dataFromTypeCfgKey],
      params: config?.params ?? {},
      reqDataType: config?.reqDataType ?? "Items",
      isEnterReqData: overrideParams?.isEnterReqData ?? config?.isEnterReqData ?? true,
    };
  } else if (["VmCode", "HttpService"].includes(config?.templateProps?.tableCommonAttr?.dataFromType)) {
    const cfg = config.templateProps.tableCommonAttr;
    retInfo.isTemplateVmConfigMatched = true;
    retInfo.config = {
      ...cfg,
      templateIdx: idx,
      [dataFromTypeCfgKey]: cfg[dataFromTypeCfgKey],
      params: cfg?.params ?? {},
      reqDataType: cfg?.reqDataType ?? "Items",
      isEnterReqData: overrideParams?.isEnterReqData ?? cfg?.isEnterReqData ?? true,
    };
  }
  return retInfo;
};

/**
 * 跟据uiOptions的配置,得到的页面的模板数据,合成对应的每个模板的元数据、data数据
 * @param {Object} config
 * @param {Object} config.resource 菜单页面、普通页面、按钮型页面
 * @param {Function} config.getMetaListAndDataCallback 对应页面uiOption中匹配的模板idx
 * @param {Number} [config.templateIdx=null] 如果为数字,则说明只有一个模板数据
 * @param {Object} config.store
 * @param {String} [config.activedVmCodeInGroup=null] 多标签时的当前激活vmCode
 * @param {String} [config.templateInnerSearchPath=null] 当前匹配模板的内部的搜索路径 必须与 templateIdx 同时使用;即单模板才能使用
 */
export default async ({
  resource,
  getMetaListAndDataCallback = async ({
    allVmTemplatesConfig,
    curResourceRealPageKey,
    store,
    globalHttpApis,
    isUseStaticResource,
    staticResource,
  }) => {},
  templateIdx = null,
  store,
  activedVmCodeInGroup = null,
  templateInnerSearchPath,
  appendReqParams,
  overrideParams,
  isUseStaticResource,
  staticResource,
}) => {
  const uiOptionsKeyAlias = resourceApiAliasConfig["uiOptionsKeyAlias"];
  const resourcePermsKeyAlias = resourceApiAliasConfig["resourcePermsKeyAlias"];
  const resourceTypeKeyAlias = resourceApiAliasConfig["resourceTypeKeyAlias"];
  const childrenKeyAlias = resourceApiAliasConfig["childrenKeyAlias"];
  const realPageFileKeyAlias = resourceApiAliasConfig["realPageFileKeyAlias"];
  const pageUiTemplateConfigsKeyAlias = resourceApiAliasConfig["pageUiTemplateConfigsKeyAlias"];
  let allTemplateMetaList = [];
  let allTemplateData = [];
  let curPageUiTemplateConfig = {};
  let pageUiTemplateConfigs = resource[uiOptionsKeyAlias]?.[pageUiTemplateConfigsKeyAlias] ?? [];
  let vaildFailureTemplateInnerSearchPath = false;
  console.log(pageUiTemplateConfigs, "模板====");
  //当templateIdx存在时过滤//不要直接过滤,因为需要index
  if (typeof templateIdx === "number") {
    pageUiTemplateConfigs = pageUiTemplateConfigs.map((config, idx) => {
      if (idx === templateIdx) {
        if (typeof templateInnerSearchPath === "string") {
          let curConfig = config;
          templateInnerSearchPath.split(".").forEach((key) => {
            curConfig = curConfig?.[key];
          });
          const curConfigKeys = curConfig ? Object.keys(curConfig) : [];
          if (curConfigKeys.length > 0) {
            return { ...curConfig, templateInnerSearchPath };
          } else {
            vaildFailureTemplateInnerSearchPath = true;
            return config;
          }
        }
        return config;
      } else {
        //占位
        return config;
      }
    });
    curPageUiTemplateConfig = pageUiTemplateConfigs[templateIdx];
  }

  if (vaildFailureTemplateInnerSearchPath) {
    return { vaildFailureTemplateInnerSearchPath };
  }

  const curResourceRealPageKey = realPageFilePathKeyFuc(
    resource[resourcePermsKeyAlias],
    2,
    resource[resourceTypeKeyAlias]
  );

  let allVmCodesRes = {};
  let allVmTemplatesConfig = [];
  if (pageUiTemplateConfigs.length > 0) {
    pageUiTemplateConfigs.forEach((config, idx) => {
      if (config) {
        const templateVmConfigInfo = getTemplateVmConfigInfo({
          config,
          idx,
          overrideParams,
        });
        if (templateVmConfigInfo.isTemplateVmConfigMatched) {
          allVmTemplatesConfig.push(templateVmConfigInfo.config);
        } else if (config.dataFromType === "ChildResourceBtn") {
          const matchedChildResourceBtn = resource[childrenKeyAlias].filter(
            (btn) =>
              config.childResourceBtnIncludes.includes(btn[resourcePermsKeyAlias]) &&
              btn[resourceTypeKeyAlias] === "Button"
          );
          const getCurBtnLink = (btn) => {
            const realPageKey = `${getCurResourceLastCode(resource, "Kebab")}/${getCurResourceLastCode(btn, "Kebab")}`;
            let mapKeyToRealPageUrl = {};
            if (store?.state?.permissionInUserPages?.activePermissionInUserPages) {
              mapKeyToRealPageUrl = store.state.permissionInUserPages.mapKeyToRealPageUrl;
            } else {
              mapKeyToRealPageUrl = store.state.permission.mapKeyToRealPageUrl;
            }
            return mapKeyToRealPageUrl[realPageKey];
          };
          const childResourceBtnMetaList = matchedChildResourceBtn.map((btn) => ({
            type: "RightArrowIcon",
            key: getCurResourceLastCode(btn, "Kebab"),
            label: btn.name,
            link: getCurBtnLink(btn),
            componentAttr: {},
          }));
          allTemplateMetaList.push({
            templateIdx: idx,
            vmCode: getCurResourceLastCode(resource),
            childResourceBtnMetaList,
          });
          allTemplateData.push({
            templateIdx: idx,
            vmCode: getCurResourceLastCode(resource),
            data: [],
          });
        } else if (
          config.dataFromType === "VmCodeConfigGroup" &&
          Array.isArray(config.entityConfigGroup) &&
          config.entityConfigGroup.every(
            (el) => typeof el === "object" && el.hasOwnProperty("vmCode") && el.hasOwnProperty("title")
          )
        ) {
          let r = config.entityConfigGroup.map((curEntityConfig) => ({
            templateIdx: idx,
            vmCode: curEntityConfig.vmCode,
            params: curEntityConfig?.params ?? {}, //TODO:FIXME: 视图模型组的分页参数怎么追加待确定
            reqDataType: curEntityConfig?.reqDataType ?? "Items",
            isEnterReqData: curEntityConfig?.isEnterReqData ?? true,
          }));
          if (activedVmCodeInGroup) {
            const matchedIdx = r.findIndex((curEntityConfig) => curEntityConfig.vmCode === activedVmCodeInGroup);
            r = [r[matchedIdx]];
            curPageUiTemplateConfig = config.entityConfigGroup[matchedIdx];
          }
          allVmTemplatesConfig = [...allVmTemplatesConfig, ...r];
        }
      }
    }); //allVmTemplatesConfig, curResourceRealPageKey, store, globalHttpApis
    allVmCodesRes = await getMetaListAndDataCallback({
      allVmTemplatesConfig,
      curResourceRealPageKey,
      store,
      globalHttpApis: globalConfig,
      templateIdx,
      appendReqParams,
      overrideParams,
      isUseStaticResource,
      staticResource,
    });
  }
  //啥都不配置时,默认使用页面的vmCode
  else if (resource[resourceTypeKeyAlias] === "Page" && !resource[realPageFileKeyAlias]) {
    const curPageVmCode = getCurResourceLastCode(resource);
    let allVmTemplatesConfig = [
      {
        templateIdx: 0,
        vmCode: curPageVmCode,
        params: {
          pageNum: 1,
          pageSize: 10,
        },
        isEnterReqData: true,
      },
    ];
    allVmCodesRes = await getMetaListAndDataCallback({
      allVmTemplatesConfig,
      curResourceRealPageKey,
      store,
      globalHttpApis: globalConfig,
      templateIdx,
      appendReqParams,
      overrideParams,
      isUseStaticResource,
      staticResource,
    });
  } else {
  }
  if (Array.isArray(allVmCodesRes.allVmCodesMetaList)) {
    allTemplateMetaList = [...allTemplateMetaList, ...allVmCodesRes.allVmCodesMetaList];
    allTemplateMetaList.sort((a, b) => a.templateIdx < b.templateIdx);
  }

  if (Array.isArray(allVmCodesRes.allVmCodesData)) {
    allTemplateData = [...allTemplateData, ...allVmCodesRes.allVmCodesData];
    allTemplateData.sort((a, b) => a.templateIdx < b.templateIdx);
  }
  return Promise.resolve({
    allTemplateMetaList,
    allTemplateData,
    curPageUiTemplateConfig,
  });
};
